$(function () {
    layui.use(['element', 'form', 'table', 'laytpl', 'layer', 'util'], function () {
        var table = layui.table,
            element = layui.element,
            form = layui.form,
            layer = layui.layer,
            $ = layui.$,
            util = layui.util,
            laytpl = layui.laytpl;

        form.render();

        //渲染表格
        table.render({
            elem: '#table',
            url: '/api/user/list',
            page: true,
            cols: [[
                {type: 'numbers'},
                {field: 'userId', sort: true, title: 'ID', minWidth: '70'},
                {field: 'userAccount', sort: true, title: '学号', minWidth: '140'},
                {field: 'userNickname', sort: true, title: '用户名'},
                {field: 'mobilePhone', sort: true, title: '手机号', minWidth: '120'},
                {field: 'email', sort: true, title: '邮箱',minWidth:'200'},
                {
                    field: 'sex', sort: true, templet: function (d) {
                        if (d.sex === "MALE") {
                            return "男";
                        } else {
                            return "女";
                        }
                    }, title: '性别', minWidth: '30'
                },
                {field: 'school', sort: true, title: '学校'},
                {field: 'campus', sort: true, title: '校区'},
                {
                    field: 'createTime', sort: true, templet: function (d) {
                        return util.toDateString(d.createTime);
                    }, title: '创建时间'
                },
                {field: 'userStatus', sort: true, templet: '#statusTpl', width: 80, title: '状态'},
                {align: 'center', toolbar: '#barTpl', minWidth: 80, title: '操作'}
            ]]
        });

        //添加按钮点击事件
        $("#addBtn").click(function () {
            showEditModel(null);
        });

        //表单提交事件
        form.on('submit(btnSubmit)', function (data) {
            var type = $("#editForm").attr("method");
            if (type === "PUT") {
                data.field.timeModified = util.toDateString(util.toDateString(new Date()));
            }
            layer.load(1);

            $.ajax({
                url: "/api/user/",
                type: type,
                contentType: "application/json;charset=UTF-8",
                data: JSON.stringify(data.field),
                dataType: "json",
                success: function (data) {
                    layer.closeAll('loading');
                    if (data.code === 0) {
                        layer.msg(data.msg, {icon: 1});
                        layer.closeAll('page');
                        table.reload('table', {});
                    } else {
                        layer.msg(data.msg, {icon: 2});
                    }
                }
            });
            return false;
        });

        //工具条点击事件
        table.on('tool(table)', function (obj) {
            var data = obj.data;
            var layEvent = obj.event;

            if (layEvent === 'edit') { //修改
                showEditModel(data);
            } else if (layEvent === 'del') { //删除
                doDelete(obj);
            } else {
            }
        });

        //监听状态开关操作
        form.on('switch(statusCB)', function (obj) {
            console.log(obj);
            updateStatus(obj);
        });

        //搜索按钮点击事件
        $("#searchBtn").click(function () {
            doSearch(table);
        });


//显示表单弹窗
        function showEditModel(data) {
            layer.open({
                type: 1,
                title: data == null ? "添加用户" : "修改用户",
                area: '400px',
                offset: '120px',
                content: $("#addModel").html()
            });
            $("#editForm")[0].reset();
            $("#editForm").attr("method", "POST");
            form.on('select(school-filter)', function (data) {
                getSubCampusList(data.value);
                renderSelectSubCampus();
                form.render();
            });
            var selectItem = "";
            if (data != null) {
                $("#editForm input[name=id]").val(data.userId);
               // $("#editForm input[name=number]").val(data.userAccount);
                $("#editForm input[name=nickname]").val(data.userNickname);
                $("#editForm input[name=phone]").val(data.mobilePhone);
                $("#editForm input[name=email]").val(data.email);
                //$("#editForm input[name=school]").val(data.school);
                //$("#editForm input[name=campus]").val(data.campus);
                $("#editForm").attr("method", "PUT");
                // console.log(data.sex);
                if ("MALE" === data.sex) {
                    $("#sexMan").attr("checked", "checked");
                    $("#sexWoman").removeAttr("checked");
                } else {
                    $("#sexWoman").attr("checked", "checked");
                    $("#sexMan").removeAttr("checked");
                }
                // getSchools();
                // renderSelectSchool(data.school);
                // renderSelectSubCampus(data.school, data.campus);

                layui.form.render('radio');
            }
            $("#btnCancel").click(function () {
                layer.closeAll();
            });
        }


        var schools = {};
        var subCampusList = {};

        function getSchools() {
            $.ajax({
                url: 'schools.json',
                async: false,
                dataType: "json",
                success: function (data) {
                    schools = data;
                }
            });
        }

        //注册表单中 选择学校 下拉框渲染
        function renderSelectSchool(selectedSchoolItem) {
            var getTpl = selectSchoolTpl.innerHTML,
                view = document.getElementById('selSchool');
            laytpl(getTpl).render(schools, function (html) {
                view.innerHTML = html;
                view.value = selectedSchoolItem;
            });
        }

        //注册表单中 选择校区 下拉框渲染
        function renderSelectSubCampus(school, selectedCampusItem) {
            var getTpl = selectSubCampusTpl.innerHTML,
                view = document.getElementById('selSubCampus');
            console.log(subCampusList);
            getSubCampusList(school);
            laytpl(getTpl).render(subCampusList, function (html) {
                view.innerHTML = html;
                view.value = selectedCampusItem;
            });
        }

        function getSubCampusList(schoolName) {
            var schoolList = schools.list;
            for (var i in schoolList) {
                if (schoolList[i].name === schoolName) {
                    subCampusList.list = schoolList[i].subCampus;
                    return;
                }
            }
        }


        // function doDelete(obj) {
        //     layer.confirm('确定要删除吗？', function (index) {
        //         layer.close(index);
        //         layer.load(1);
        //         $.ajax({
        //             url: "api/user/" + obj.data.userId,
        //             type: "DELETE",
        //             dataType: "JSON",
        //             success: function (data) {
        //                 layer.closeAll('loading');
        //                 if (data.code == 200) {
        //                     layer.msg(data.msg, {icon: 1});
        //                     obj.del();
        //                 } else {
        //                     layer.msg(data.msg, {icon: 2});
        //                 }
        //             }
        //         });
        //     });
        // }

//更改状态
        function updateStatus(obj) {
            layer.load(1);
            var newStatus = obj.elem.checked ? 0 : 1;
            var user = {};

            user["status"] =  newStatus;
            user["timeModified"] =  util.toDateString(new Date());
            user["id"] =  obj.elem.value;

            $.ajax({
                type: "PUT",
                url: "/api/user/",
                contentType: 'application/json;charset=UTF-8',
                data: JSON.stringify(user),
                dataType: "json",
                cache: false,
                success: function (ret) {
                    layer.closeAll('loading');
                    if (ret.code === 0) {
                        table.reload('table', {});
                    } else {
                        layer.msg(ret.msg, {icon: 2});
                        table.reload('table', {});
                    }
                }
            });
        }

//搜索
    function doSearch(table) {
        var key = $("#searchKey").val();
        var value = $("#searchValue").val();
        if (value == '') {
            key = '';
        }
        table.reload('table', {where: {searchKey: key, searchValue: value}});
    }

//删除
    function doReSet(userId) {
        layer.confirm('确定要重置密码吗？', function (index) {
            layer.close(index);
            layer.load(1);
            $.post("api/user/psw/" + userId, {
                token: getToken(),
                _method: "PUT"
            }, function (data) {
                layer.closeAll('loading');
                if (data.code == 200) {
                    layer.msg(data.msg, {icon: 1});
                } else {
                    layer.msg(data.msg, {icon: 2});
                }
            }, "JSON");
        });
    }

});
})
;
